/**
 * 侦探助手智能体
 * 专门用于分析案件线索和证据的智能助手
 */
import { BaseAgent } from '../core/BaseAgent';

interface Evidence {
  id: string;
  type: string;
  content: string;
  source: string;
  reliability: number;
  timestamp?: string;
}

interface ReasoningResult {
  analysis: string;
  confidence: number;
  contradictions?: Array<{
    evidence1: string;
    evidence2: string;
    reason: string;
  }>;
  suggestions?: string[];
}

export class DetectiveAssistant extends BaseAgent {
  /**
   * 执行证据分析任务
   * @param input 输入数据，包含证据列表
   * @returns 分析结果
   */
  async execute(input: {
    evidences: Evidence[];
    task?: string;
    question?: string;
  }): Promise<ReasoningResult> {
    try {
      console.log(`[DetectiveAssistant] 开始分析 ${input.evidences.length} 条证据`);
      
      // 根据任务类型执行不同的分析
      if (input.task === 'analyze_evidence') {
        return this.analyzeEvidence(input.evidences);
      } else if (input.task === 'detect_contradictions') {
        return this.detectContradictions(input.evidences);
      } else if (input.question) {
        return this.answerQuestion(input.evidences, input.question);
      } else {
        // 默认执行全面分析
        return this.comprehensiveAnalysis(input.evidences);
      }
    } catch (error) {
      console.error('[DetectiveAssistant] 分析过程中出现错误:', error);
      return {
        analysis: `分析过程中出现错误: ${error instanceof Error ? error.message : String(error)}`,
        confidence: 0
      };
    }
  }

  /**
   * 分析证据
   * @param evidences 证据列表
   * @returns 分析结果
   */
  private analyzeEvidence(evidences: Evidence[]): ReasoningResult {
    // 过滤掉低可靠性的证据
    const confidenceThreshold = this.getParameter('confidence_threshold') || 0.5;
    const reliableEvidences = evidences.filter(e => e.reliability >= confidenceThreshold);
    
    // 按类型对证据进行分组
    const evidenceByType = this.groupEvidenceByType(reliableEvidences);
    
    // 生成分析报告
    let analysis = `我已分析了 ${reliableEvidences.length} 条可靠证据，发现了以下关键信息：\n\n`;
    
    // 分析每种类型的证据
    for (const [type, typeEvidences] of Object.entries(evidenceByType)) {
      analysis += `【${this.getEvidenceTypeLabel(type)}】(${typeEvidences.length}条)\n`;
      typeEvidences.forEach(evidence => {
        analysis += `- ${evidence.content} (来源: ${evidence.source}, 可信度: ${(evidence.reliability * 100).toFixed(0)}%)\n`;
      });
      analysis += '\n';
    }
    
    // 计算整体可信度
    const avgReliability = reliableEvidences.reduce((sum, e) => sum + e.reliability, 0) / reliableEvidences.length;
    
    return {
      analysis,
      confidence: avgReliability,
      suggestions: this.generateSuggestions(evidences)
    };
  }

  /**
   * 检测证据之间的矛盾
   * @param evidences 证据列表
   * @returns 矛盾检测结果
   */
  private detectContradictions(evidences: Evidence[]): ReasoningResult {
    const contradictions: ReasoningResult['contradictions'] = [];
    
    // 简单的矛盾检测逻辑
    for (let i = 0; i < evidences.length; i++) {
      for (let j = i + 1; j < evidences.length; j++) {
        const evidence1 = evidences[i];
        const evidence2 = evidences[j];
        
        // 检查内容是否矛盾（这里使用简单的关键词匹配）
        if (this.checkContentContradiction(evidence1.content, evidence2.content)) {
          contradictions.push({
            evidence1: evidence1.id,
            evidence2: evidence2.id,
            reason: `证据 ${evidence1.id} 和 ${evidence2.id} 在内容上存在矛盾`
          });
        }
        
        // 检查时间矛盾（如果有时戳）
        if (evidence1.timestamp && evidence2.timestamp) {
          if (this.checkTimeContradiction(evidence1, evidence2)) {
            contradictions.push({
              evidence1: evidence1.id,
              evidence2: evidence2.id,
              reason: `证据 ${evidence1.id} 和 ${evidence2.id} 在时间线上存在矛盾`
            });
          }
        }
      }
    }
    
    let analysis = `矛盾检测完成。`;
    if (contradictions.length > 0) {
      analysis += ` 发现了 ${contradictions.length} 处潜在矛盾：\n\n`;
      contradictions.forEach((contradiction, index) => {
        analysis += `${index + 1}. ${contradiction.reason}\n`;
      });
    } else {
      analysis += ` 未发现明显矛盾。\n`;
    }
    
    return {
      analysis,
      confidence: contradictions.length > 0 ? 0.85 : 0.9,
      contradictions
    };
  }

  /**
   * 回答关于证据的问题
   * @param evidences 证据列表
   * @param question 问题
   * @returns 回答结果
   */
  private answerQuestion(evidences: Evidence[], question: string): ReasoningResult {
    // 简单的问题回答逻辑
    const relevantEvidences = evidences.filter(evidence => 
      this.isEvidenceRelevantToQuestion(evidence, question)
    );
    
    let analysis = `根据提供的证据，我对问题「${question}」的回答如下：\n\n`;
    
    if (relevantEvidences.length > 0) {
      analysis += `相关证据分析：\n`;
      relevantEvidences.forEach(evidence => {
        analysis += `- ${evidence.content} (来源: ${evidence.source})\n`;
      });
      
      // 基于相关证据生成回答
      analysis += `\n基于以上证据，我的结论是：${this.generateAnswerFromEvidence(relevantEvidences, question)}\n`;
    } else {
      analysis += `没有找到与问题直接相关的证据。\n`;
    }
    
    return {
      analysis,
      confidence: relevantEvidences.length > 0 ? 0.75 : 0.3
    };
  }

  /**
   * 综合分析
   * @param evidences 证据列表
   * @returns 综合分析结果
   */
  private comprehensiveAnalysis(evidences: Evidence[]): ReasoningResult {
    // 结合多种分析方法
    const evidenceAnalysis = this.analyzeEvidence(evidences);
    const contradictionResult = this.detectContradictions(evidences);
    
    let analysis = `## 综合分析报告\n\n`;
    analysis += evidenceAnalysis.analysis + `\n`;
    analysis += contradictionResult.analysis + `\n`;
    
    // 计算综合可信度
    const confidence = (evidenceAnalysis.confidence + contradictionResult.confidence) / 2;
    
    return {
      analysis,
      confidence,
      contradictions: contradictionResult.contradictions,
      suggestions: evidenceAnalysis.suggestions
    };
  }

  /**
   * 辅助方法：按类型分组证据
   */
  private groupEvidenceByType(evidences: Evidence[]): Record<string, Evidence[]> {
    return evidences.reduce((groups, evidence) => {
      const type = evidence.type;
      if (!groups[type]) {
        groups[type] = [];
      }
      groups[type].push(evidence);
      return groups;
    }, {} as Record<string, Evidence[]>);
  }

  /**
   * 辅助方法：获取证据类型标签
   */
  private getEvidenceTypeLabel(type: string): string {
    const labels: Record<string, string> = {
      'physical': '物证',
      'witness': '证人证词',
      'document': '文件证据',
      'digital': '数字证据',
      'circumstantial': '间接证据'
    };
    return labels[type] || type;
  }

  /**
   * 辅助方法：生成建议
   */
  private generateSuggestions(evidences: Evidence[]): string[] {
    const suggestions: string[] = [];
    
    // 检查证据是否足够全面
    if (evidences.length < 5) {
      suggestions.push('建议收集更多证据以支持分析结论');
    }
    
    // 检查低可靠性证据
    const lowReliability = evidences.filter(e => e.reliability < 0.5);
    if (lowReliability.length > 0) {
      suggestions.push(`发现 ${lowReliability.length} 条低可靠性证据，建议进一步核实这些信息`);
    }
    
    return suggestions;
  }

  /**
   * 辅助方法：检查内容矛盾
   */
  private checkContentContradiction(content1: string, content2: string): boolean {
    // 简单的关键词匹配逻辑
    const contradictionPairs = [
      ['在现场', '不在现场'],
      ['看到', '没看到'],
      ['是', '不是'],
      ['有', '没有']
    ];
    
    for (const [word1, word2] of contradictionPairs) {
      if (content1.includes(word1) && content2.includes(word2)) {
        return true;
      }
    }
    
    return false;
  }

  /**
   * 辅助方法：检查时间矛盾
   */
  private checkTimeContradiction(evidence1: Evidence, evidence2: Evidence): boolean {
    // 这里只是简单示例，实际应该有更复杂的时间分析逻辑
    return false;
  }

  /**
   * 辅助方法：检查证据是否与问题相关
   */
  private isEvidenceRelevantToQuestion(evidence: Evidence, question: string): boolean {
    // 简单的关键词匹配
    return evidence.content.toLowerCase().includes(question.toLowerCase());
  }

  /**
   * 辅助方法：基于证据生成回答
   */
  private generateAnswerFromEvidence(evidences: Evidence[], question: string): string {
    // 基于相关证据生成简单回答
    const keywords = ['凶手', '动机', '时间', '地点', '方法'];
    
    for (const keyword of keywords) {
      if (question.includes(keyword)) {
        const relevantEvidence = evidences.find(e => e.content.includes(keyword));
        if (relevantEvidence) {
          return `根据 ${relevantEvidence.source} 的信息，${relevantEvidence.content}`;
        }
      }
    }
    
    return '基于现有证据，无法得出明确结论，建议收集更多相关信息。';
  }
}
